//
//  baseWeChatManager.m
//  baseVC
//
//  Created by 陶磊 on 2019/12/16.
//  Copyright © 2019 QHT. All rights reserved.
//

#import "baseWeChatManager.h"

NSString *const baseWeChatCallBackNotification = @"baseWeChatCallBackNotification";
NSString *const baseWeChatPayCallBackNotification = @"baseWeChatPayCallBackNotification";
NSString *const baseWeChatInvoiceCallBackNotification = @"baseWeChatInvoiceCallBackNotification";


NSString *const baseWeChatAppID = @"wxe197adb2504a488f";
NSString *const baseWeChatAPPSecret = @"2e856d94497ef0689f8a10cf651cfc1a";
//NSString *const ZHUWeChatGrantType = @"authorization_code";

// url
//NSString *const ZHUWeChatAccessTokenURL = @"https://api.weixin.qq.com/sns/oauth2/access_token";
//NSString *const ZHUWeChatSnsUserInfoURL = @"https://api.weixin.qq.com/sns/userinfo";

// 微信公众平台接口
NSString *const baseWeChatCGIBinTokenURL = @"https://api.weixin.qq.com/cgi-bin/token";
NSString *const baseWeChatCardGetInvoiceinfoURL = @"https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=wx_card&access_token=";
NSString *const baseWeChatGetInvoiceBatchURL = @"https://api.weixin.qq.com/card/invoice/reimburse/getinvoicebatch?access_token=";

@interface baseWeChatManager()

@end



@implementation baseWeChatManager

+ (baseWeChatManager *)getInstance
{
    static baseWeChatManager *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[baseWeChatManager alloc] init];
    });
    return _sharedInstance;
}

+ (BOOL)isWeChatInstalled
{
    return [WXApi isWXAppInstalled];
}

+ (void)getWeChatAccessToken
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //上文提供的wxe197adb2504a488f
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html", nil];
    
    NSDictionary *paraDic = @{
                              @"grant_type": @"client_credential",
                              @"appid": baseWeChatAppID,
                              @"secret": baseWeChatAPPSecret
                              };
    [manager GET:baseWeChatCGIBinTokenURL parameters:paraDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
        NSDictionary *dic = responseObject;
        [self getInstance].accessToken = responseObject[@"access_token"];
        //            [self getWxApi_ticket:dic];
//        [ab setObject:dic[@"access_token"] forKey:@"access_token"];
//        [self requestTickets:ab];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)pay:(NSDictionary *)dic
{
    NSDictionary *paraDic = @{
                              @"id": dic[@"id"]
                              };
    [baseToast makeActivityOnTheWindow];
    [baseHttpClient requestPOST:@"" parameters:paraDic isNeedlogin:YES success:^(id data, long code, NSString *msgString) {
        [baseToast hideActivityOnTheWindow];
        
        NSInteger status = [data[@"statu"] integerValue];
        
        if (status == 1) {
            NSDictionary *contentDic = data[@"data"];
            PayReq *request = [[PayReq alloc] init];
            request.partnerId = contentDic[@"partnerid"];
            request.prepayId = contentDic[@"prepayid"];
            request.package = contentDic[@"package"];
            request.nonceStr = contentDic[@"noncestr"];
            request.timeStamp = [contentDic[@"timestamp"] intValue];
            request.sign= contentDic[@"sign"];
//            [WXApi sendReq:request];
        }
    
    } failure:^(id data, long code, NSString *msgString) {
        [baseToast hideActivityOnTheWindow];
        [baseToast makeOnTheWindow:data[@"msg"]];
    }];
}

- (void)share:(NSDictionary *)dic
{
    NSString *title = dic[@"title"];
    if (!title.length) {
        [baseToast makeOnTheWindow:@"分享失败，没有标题"];
        return;
    }

    //创建多媒体对象
    NSString *shareUrlStr = dic[@"shareUrlStr"]; //分享链接
    if (!shareUrlStr.length) {
        [baseToast makeOnTheWindow:@"分享失败，没有链接"];
        return;
    }
    
    WXWebpageObject *webObj = [WXWebpageObject object];
    webObj.webpageUrl = shareUrlStr;//分享链接
    
    WXMediaMessage *message = [[WXMediaMessage alloc] init];
    message.title = title;
    message.description = dic[@"description"];
    [message setThumbImage:[UIImage imageNamed:@"app_logo"]];
    message.mediaObject = webObj;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
    // 是否是文档
    req.bText =  NO;
    req.message = message;
//    [WXApi sendReq:req];
}


// 分享
+ (void)weChatShare:(NSDictionary *)dic
{
    [baseToast makeActivityOnTheWindow];
    [baseHttpClient requestPOST:@"" parameters:nil isNeedlogin:YES success:^(id data, long code, NSString *msgString) {
        [baseToast hideActivityOnTheWindow];
        
        NSInteger status = [data[@"statu"] integerValue];
        if (status == 1) {
            NSString *shareUrlStr = data[@"data"];
            
            NSMutableDictionary *weChatShareDic = [NSMutableDictionary dictionaryWithDictionary:dic];
            [weChatShareDic setValue:shareUrlStr forKey:@"shareUrlStr"];
            
            [[baseWeChatManager getInstance] share:weChatShareDic];
        }
    } failure:^(id data, long code, NSString *msgString) {
        [baseToast hideActivityOnTheWindow];
    }];
}

#pragma mark -- 拉取发票信息
+ (void)getInvoiceinfo:(NSDictionary *)dic
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSMutableDictionary *mudic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"wx_card", @"type", nil];
    //上文提供的wxe197adb2504a488f
    
    
    [mudic setObject: dic[@"access_token"] forKey:@"access_token"];
    
    NSString *str = [NSString stringWithFormat:@"%@%@", baseWeChatCardGetInvoiceinfoURL, dic[@"access_token"]];
    [manager GET:str parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *ticket = [responseObject objectForKey:@"ticket"];
        NSLog(@"ticket=%@",ticket);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}




@end
